package com.chouxiaozi.miniprogram.controller;

import com.alibaba.fastjson.JSONObject;
import com.chouxiaozi.miniprogram.bean.JsonResult;
import com.chouxiaozi.miniprogram.config.ApplicationConfig;
import com.chouxiaozi.miniprogram.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FaceController {

    @Autowired
    BdTokenUtil bdTokenUtil;

    @Autowired
    ApplicationConfig applicationConfig;

    /**
     * 人脸检测
     * @param file
     * @return
     */
    @PostMapping("/face_detect")
    public JsonResult token(@RequestParam("file") MultipartFile file){
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect";

        String accessToken = bdTokenUtil.getAuth(applicationConfig.getBdAk(), applicationConfig.getBdFaceSk());
        Map<String, String> map = new HashMap<>();
        String image = "";
        try {
            image = Base64Util.encode(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put("image", image);
        map.put("image_type", "BASE64");
        map.put("face_field", "age,beauty,expression,faceshape,gender,glasses,race,quality,emotion,facetype,mask,spoofing");
        // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。

        String result = null;
        try {
            result = HttpUtil.post(url, accessToken, "application/json", GsonUtils.toJson(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return JsonResult.success(result);
    }

}
